package cn.tedu._07vehicle.base.exception;

import cn.tedu._07vehicle.base.response.JsonResult;
import cn.tedu._07vehicle.base.response.StatusCode;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

/**
 * ControllerAdvice注解:
 *   1.标识该类为全局异常处理器的类;
 *   2.当控制器抛出异常时,框架优先检查是否定义了全局异常处理器;
 * RestControllerAdvice注解:
 *   1.组合注解,等价于@ControllerAdvice + @ResponseBody;
 *   2.在类上添加该注解后,所有的异常处理方法上无须再添加 @ResponseBody 注解了;
 * 异常处理顺序:
 *   1.控制器抛出异常后,框架先检查是否定义了全局异常处理器;
 *   2.如果有,则到该类中定义对应的异常处理方法;
 *   3.如果没有该异常的处理方法,则找该异常父类异常的异常处理方法;
 *   4.如果父类的也没有对应的异常处理方法,则会找能够处理所有异常的Throwable异常处理方法;
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    public JsonResult doHandlerIllegalArgumentException(IllegalArgumentException ex){
        String data = ex.getMessage();
        log.error("IllegalArgumentException:"+data);
        return new JsonResult(StatusCode.OPERATION_FAILED,data);
    }
    @ExceptionHandler(RuntimeException.class)
    public JsonResult doHandlerRuntimeException(RuntimeException ex){
        String data = ex.getMessage();
        log.error("RuntimeException:"+data);
        return new JsonResult(StatusCode.OPERATION_FAILED,data);
    }

    /**
     *
     * MethodArgumentNotValidException
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult doHandlerMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        String data = ex.getFieldError().getDefaultMessage();
        log.error(data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }
    /**
     * 异常处理方法:Spring Validation 验证非封装参数
     * ConstraintViolationException
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public JsonResult doHandlerConstraintViolationException(ConstraintViolationException ex){
        String data = ex.getMessage().split(":")[1].trim();
        log.error("ConstraintViolationException:"+data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public JsonResult doHandlerMaxUploadSizeExceededException(MaxUploadSizeExceededException ex){
        String data = "文件超出限制,单个文件上传大小不能超过100MB";
        log.error("MaxUploadSizeExceededException:"+data);
        return new JsonResult(StatusCode.UPLOAD_FILE_ERROR,data);
    }
//    @ExceptionHandler(Throwable.class)
//    public JsonResult doHandlerThrowable(Throwable ex){
//        String data = ex.getMessage();
//        log.error("Throwable:"+data);
//        return new JsonResult(StatusCode.THROWABLE_ERROR,data);
//    }
}
